import type { Request, ResponseToolkit } from "@hapi/hapi";
import Hapi from "@hapi/hapi";
import { TemCateDetails, TempalteCate, TempalteList } from "../../model/index";

let route: Hapi.ServerRoute<Hapi.ReqRefDefaults> = {
  path: "/addTempDetails",
  method: "post",
  handler: async (r: any, h: ResponseToolkit) => {
    try {
      const payload = r.payload;
      let tempalteCate: any = await TempalteCate.findOne({
        _id: payload.cateId,
      });
      let noteInfo: any = await new TempalteList({
        temTitle: payload.temTitle,
        temImage: payload.temImage,
      });
      let temCateDetails = await new TemCateDetails({
        ...payload.details,
      });

      await tempalteCate.temList.push(noteInfo._id);
      await noteInfo.details.push(temCateDetails._id);
      await noteInfo.save();
      await tempalteCate.save();
      await temCateDetails.save();

      return { code: 200, data: true, message: "添加成功" };
    } catch (err: any) {
      console.log(err);
      return err;
    }
  },
  options: {
    payload: {
      parse: true, // 解析请求体
      allow: "application/json", // 允许JSON格式的请求体
    },
    plugins: {
      "hapi-swagger": {
        security: [{ apiKey: [] }],
      },
    },
    tags: ["api"],
  },
};
export default route;
